package com.newtype.meeting.server.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.newtype.meeting.client.model.Account;
import com.newtype.meeting.client.model.Department;
import com.newtype.meeting.client.model.Member;
import com.newtype.meeting.client.service.AccountService;
import com.newtype.meeting.server.PMF;
import com.newtype.meeting.shared.AccountDTO;
import com.newtype.meeting.shared.AccountSummaryDTO;

/**
 * 帐户信息业务逻辑实现类
 * @author 汪恭泽
 * Jun 3, 2011 10:03:33 AM
 */
public class AccountServiceImpl extends RemoteServiceServlet implements
		AccountService {
	private static final long serialVersionUID = -7534892646720931337L;

	@Override
	public AccountDTO getAccount(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Account dsAccount, detached;

		try {
			dsAccount = pm.getObjectById(Account.class, id);
			dsAccount.getDetails();
			detached = pm.detachCopy(dsAccount);
		} finally {
			pm.close();
		}
		return detached.toDTO();
	}

	@Override
	public AccountDTO updateAccount(AccountDTO accountDTO) {
		if (accountDTO.getId() == null) {//create new
			Account newAccount = addAccount(accountDTO);
			return newAccount.toDTO();
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Account account = null;
		try {
			account = pm.getObjectById(Account.class, accountDTO.getId());
			account.updateFromDTO(accountDTO);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return accountDTO;
	}

	//create new Account object in Datastore.
	private Account addAccount(AccountDTO accountDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Account account = null;
		try {
			account = new Account(accountDTO);
			pm.makePersistent(account);
		} finally {
			pm.close();
		}
		return account;
	}

	@Override
	public void addAccount(Account account) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(account);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Account checkLogin(HashMap<String, String> loginInfo) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Account.class, "accountID == username");
		query.declareParameters("String username");
		try {
			List<Account> users = (List<Account>) query.execute(loginInfo
					.get("userName"));
			return (users != null && users.size() == 1 && users.get(0)
					.getPassword().equals(loginInfo.get("password"))) ? users
					.get(0) : null;
		} finally {
			pm.close();
		}
	}

	@Override
	public Boolean deleteAccount(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Account account = pm.getObjectById(Account.class, id);
			pm.deletePersistent(account);
		} finally {
			pm.close();
		}
		return true;
	}

	@Override
	public PagingLoadResult<AccountSummaryDTO> getAccounts(
			PagingLoadConfig config, String status) {
		List<AccountSummaryDTO> list = getAccountSummaries(status);
		List<AccountSummaryDTO> sublist = new ArrayList<AccountSummaryDTO>();

		int start = config.getOffset();//得到当前页
		int limit = list.size();

		//使用min方法取两个数值的最小量，然后哦得到偏移量
		if (config.getLimit() > 0) {
			limit = Math.min(start + config.getLimit(), limit);
		}
		//根据偏移量从list集合中取部分数据然后装载到sublist集合中
		for (int i = config.getOffset(); i < limit; i++) {
			sublist.add(list.get(i));
		}
		return new BasePagingLoadResult<AccountSummaryDTO>(sublist, config
				.getOffset(), list.size());
	}

	@SuppressWarnings("unchecked")
	public List<Account> getAccounts(Integer status) {
		List<Account> accounts = new ArrayList<Account>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Account.class, "status == param");
		query.declareParameters("String param");
		List<Account> results = (List<Account>) query.execute(status);
		accounts = (List<Account>) pm.detachCopyAll(results);
		return accounts;
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<AccountSummaryDTO> getAccountSummaries(String status) {
		ArrayList<AccountSummaryDTO> accountSummaries = new ArrayList<AccountSummaryDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Account.class, "status == keys");
			query.declareParameters("String keys");
			List<Account> accounts = (List<Account>) query.execute(status);
			for (Account account : accounts) {
				accountSummaries.add(account.toLightWeightDTO());
			}
		} finally {
			pm.close();
		}
		return accountSummaries;
	}

	/**
	 * 根据职称ID返回Account集合
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<AccountSummaryDTO> getAccountsByTitleID(String titleID) {
		ArrayList<AccountSummaryDTO> toReturn = new ArrayList<AccountSummaryDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Account.class, "title == keyword");
			query.declareParameters("String keyword");
			List<Account> result = (List<Account>) query.execute(titleID);
			for (Account account : result) {
				toReturn.add(account.toLightWeightDTO());
			}
			for (AccountSummaryDTO a : toReturn) {
				if (a.getDeptID() != null && !a.getDeptID().equals("")) {
					a.setDeptName(getDept(a.getDeptID()).getDeptName());
				}
				a.updateProperties();
			}

		} finally {
			pm.close();
		}
		return toReturn;
	}

	/**
	 * 根据部门ID返回该部门信息
	 * @param deptID
	 * @return
	 */
	public Department getDept(String deptID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		return pm.getObjectById(Department.class, deptID);

	}

	/**
	 * 检查用户名是否存在
	 */
	@SuppressWarnings("unchecked")
	public Boolean checkExist(String accountID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Account.class, "accountID == keyword");
			query.declareParameters("String keyword");
			List<Department> result = (List<Department>) query
					.execute(accountID);
			if (result.size() > 0 && result != null) {
				return true;
			}
		} finally {
			pm.close();
		}
		return false;
	}

	/**
	 * 保存人员兼职信息
	 */
	public void saveMember(Member member) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(member);
		} finally {
			pm.close();
		}
	}

	/**
	 * 获取AccountSummaryDTO
	 */
	public AccountSummaryDTO getAccountSummaryDTO(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		AccountSummaryDTO dto;
		try {
			Account account = pm.getObjectById(Account.class, id);
			dto = new AccountSummaryDTO(account.getId(),
					account.getAccountID(), account.getFullName(), account
							.getDeptID());
			if (dto.getDeptID() != null && !dto.getDeptID().equals("")) {
				dto.setDeptName(getDept(dto.getDeptID()).getDeptName());
			}
		} finally {
			pm.close();
		}
		return dto;
	}

	/**
	 * 通过AccountID获取该帐户信息
	 */
	@SuppressWarnings("unchecked")
	public Account getAccountByAccountID(String accountID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Account> toReturn = new ArrayList<Account>();
		try {
			Query query = pm.newQuery(Account.class, "accountID == keyword");
			query.declareParameters("String keyword");
			List<Account> result = (List<Account>) query.execute(accountID);
			toReturn = (List<Account>) pm.detachCopyAll(result);
			return toReturn.get(0);
		} finally {
			pm.close();
		}
	}

	/**
	 * 功能：通过邮箱获取该用户信息
	 */
	@SuppressWarnings("unchecked")
	public Account getAccountByEmail(String email) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Account> toReturn = new ArrayList<Account>();
		try {
			Query query = pm.newQuery(Account.class, "email == parameter");
			query.declareParameters("String parameter");
			List<Account> result = (List<Account>) query.execute(email);
			toReturn = (List<Account>) pm.detachCopyAll(result);
			return toReturn.get(0);
		} finally {
			pm.close();
		}
	}
	
	
}
